package com.lxs;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class NetworkScanner {
    public static void main(String[] args) {
        scanLocalNetwork();
    }

    public static void scanLocalNetwork() {
        ExecutorService executor = Executors.newFixedThreadPool(20);
        String networkPrefix = "192.168.1."; // 根据你的网络修改

        for (int i = 1; i < 255; i++) {
            String ip = networkPrefix + i;
            executor.execute(new HostScanner(ip));
        }

        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class HostScanner implements Runnable {
        private String ip;

        public HostScanner(String ip) {
            this.ip = ip;
        }

        @Override
        public void run() {
            try {
                InetAddress address = InetAddress.getByName(ip);
                if (address.isReachable(1000)) { // 1秒超时
                    System.out.println("活跃主机: " + ip);
                    try {
                        String hostname = address.getHostName();
                        if (!hostname.equals(ip)) {
                            System.out.println("  主机名: " + hostname);
                        }
                    } catch (Exception e) {
                        // 忽略主机名解析失败
                    }
                }
            } catch (Exception e) {
                // 忽略不可达的主机
            }
        }
    }
}
